package com.fulu.game.bi.common.util.math;

import com.fulu.game.bi.common.util.lang.StringUtils;

import java.math.BigDecimal;
import java.util.Objects;

public final class MathUtils {
    private MathUtils() {
    }

    public static BigDecimal ratio(Integer numerator, Integer denominator) {
        if (Objects.isNull(numerator) || Objects.isNull(denominator) || denominator == 0) {
            return BigDecimal.ZERO;
        }
        final BigDecimal val1 = BigDecimal.valueOf(numerator);
        final BigDecimal val2 = BigDecimal.valueOf(denominator);
        return ratio(val1, val2);
    }

    public static BigDecimal ratio(BigDecimal numerator, BigDecimal denominator) {
        if (Objects.isNull(numerator) || Objects.isNull(denominator) || BigDecimal.ZERO.equals(denominator)) {
            return BigDecimal.ZERO;
        }

        return numerator.divide(denominator, 2, BigDecimal.ROUND_HALF_DOWN);
    }

    public static BigDecimal chainRatio(Integer numerator, Integer denominator) {
        if (Objects.isNull(numerator) || Objects.isNull(denominator) || denominator == 0) {
            return BigDecimal.ZERO;
        }
        final BigDecimal val1 = BigDecimal.valueOf(numerator);
        final BigDecimal val2 = BigDecimal.valueOf(denominator);
        return ratio(val1, val2).subtract(BigDecimal.ONE);
    }

    public static BigDecimal chainRatio(BigDecimal numerator, BigDecimal denominator) {
        if (Objects.isNull(numerator) || Objects.isNull(denominator) || BigDecimal.ZERO.equals(denominator)) {
            return BigDecimal.ZERO;
        }

        return numerator.divide(denominator, 2, BigDecimal.ROUND_HALF_DOWN).subtract(BigDecimal.ONE);
    }

    /**
     * 处理还有百分号的字符串的比率
     * @param numeratorStr
     * @param denominatorStr
     * @return
     */
    public static String percentRatio(String numeratorStr, String denominatorStr) {
        BigDecimal numerator = StringUtils.isBlank(numeratorStr) ? null : new BigDecimal(numeratorStr.substring(0, numeratorStr.length() - 1));
        BigDecimal denominator = StringUtils.isBlank(denominatorStr) ? null : new BigDecimal(denominatorStr.substring(0, denominatorStr.length() - 1));
        if (Objects.isNull(numerator) || Objects.isNull(denominator) || BigDecimal.ZERO.equals(denominator)) {
            return "0";
        }
        return numerator.divide(denominator, 2, BigDecimal.ROUND_HALF_DOWN).subtract(BigDecimal.ONE).toString();
    }

    /**
     * 字符串转百分比
     * @param ratioStr
     * @return
     */
    public static String str2Ratio(String ratioStr) {
        if (StringUtils.isBlank(ratioStr)) {
            return "0.00%";
        }
        BigDecimal bigDecimal = new BigDecimal(ratioStr);
        return bigDecimal.multiply(BigDecimal.valueOf(100)).toString() + "%";
    }



}
